package no.aina.skiforeningen;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import no.aina.xml.XMLReader;
import no.aina.xml.XMLReaderException;

public class XMLFiles {

   private Map<String, XMLFile> files;

   private static XMLFiles xmlFiles = new XMLFiles();
   
   private XMLFiles() {
      files = new HashMap<String, XMLFile>();
   }
   
   public static XMLFiles getXMLFiles() {
      if (xmlFiles == null) {
         xmlFiles = new XMLFiles();
      }
      return xmlFiles;
   }

   public XMLReader retrieveXML(String url) throws XMLReaderException {

      if (files.containsKey(url)) {
         XMLFile file = files.get(url);
         Calendar today = Calendar.getInstance();
         today.setTime(new Date());

         Calendar cal = Calendar.getInstance();
         cal.setTime(file.date);

         if (today.get(Calendar.YEAR) == cal.get(Calendar.YEAR) && today.get(Calendar.MONTH) == cal.get(Calendar.MONTH)
               && today.get(Calendar.DAY_OF_MONTH) == cal.get(Calendar.DAY_OF_MONTH) && cal.get(Calendar.HOUR_OF_DAY) > 9) {

            return file.content;
         }
      }

      XMLReader xml = new XMLReader(url);
      XMLFile file = new XMLFile();
//      file.url = url;
      file.content = xml;
      file.date = new Date();

      files.put(url, file);

      return xml;

   }

   private class XMLFile {
//      private String url;
      private Date date;
      private XMLReader content;
   }
}
